package com.incar.chuxing.activity.driving;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.WebViewActivity;
import com.incar.chuxing.activity.personal.ContactServiceActivity;
import com.incar.chuxing.activity.personal.DebugModeActivity;
import com.incar.chuxing.activity.personal.LoginActivity;
import com.incar.chuxing.activity.personal.TravelRecordActivity;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.ParseApiStore;
import com.incar.chuxing.api.RxApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.baiduMap.BaiduMapParams;
import com.incar.chuxing.baiduMap.LocationFilter;
import com.incar.chuxing.baiduMap.MapStatusUtils;
import com.incar.chuxing.baiduMap.MarkerOverlay.MarkerOverlay;
import com.incar.chuxing.baiduMap.MarkerOverlay.OverlayUtils;
import com.incar.chuxing.baiduMap.RoutePlan;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.AvatarEvent;
import com.incar.chuxing.bean.CarDamageBean;
import com.incar.chuxing.bean.CheckPeccancyBean;
import com.incar.chuxing.bean.CityBoundBean;
import com.incar.chuxing.bean.CityDetailBean;
import com.incar.chuxing.bean.CurrentFeeBean;
import com.incar.chuxing.bean.GoldCarOneBean;
import com.incar.chuxing.bean.OperateBean;
import com.incar.chuxing.bean.PecancyRedDotBean;
import com.incar.chuxing.bean.RechargeDotBean;
import com.incar.chuxing.bean.ReturnCarBean;
import com.incar.chuxing.bean.ReturnCarEvent;
import com.incar.chuxing.bean.SendTelBean;
import com.incar.chuxing.bean.TravelDetailBean;
import com.incar.chuxing.bean.TravelDistanceBean;
import com.incar.chuxing.bean.WalletRedDotBean;
import com.incar.chuxing.utils.AntiShake;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.Dialogs.CarCurrentParkFeeDialog;
import com.incar.chuxing.utils.Dialogs.ChooseNaviDialog;
import com.incar.chuxing.utils.Dialogs.DialogOneButton;
import com.incar.chuxing.utils.Dialogs.DialogTwoButton;
import com.incar.chuxing.utils.ImageLoader;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.NetUtils;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.TimeUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.utils.ble.BleConstants;
import com.incar.chuxing.utils.ble.BluetoothHelper;
import com.incar.chuxing.utils.wangyiqiyu.ConsultService;
import com.incar.chuxing.widget.MarqueeTextview;
import com.qiyukf.unicorn.api.Unicorn;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.incar.chuxing.utils.ble.BluetoothHelper.REQUEST_OPEN_BLE;

public class DrivingActivity extends BaseActivity implements OnGetPoiSearchResultListener {

    @BindView(R.id.driving_car_close)
    ImageButton drivingCarClose;
    @BindView(R.id.driving_car_open)
    ImageButton drivingCarOpen;
    @BindView(R.id.driving_car_return)
    ImageView drivingCarReturn;
    @BindView(R.id.driving_car_find)
    ImageButton drivingCarFind;
    @BindView(R.id.tv_inUse_license)
    TextView tvInUseLicense;
    @BindView(R.id.progress_bar_in_use)
    RelativeLayout progressBarInUse;
    @BindView(R.id.imageView_locate)
    ImageView imageViewLocate;
    @BindView(R.id.imageView_center)
    ImageView imageViewCenter;
    @BindView(R.id.park_fee_tip)
    TextView parkFeeTip;
    @BindView(R.id.info_image_head)
    ImageView imageViewHead;
    @BindView(R.id.center_username)
    TextView centerUsername;

    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    @BindView(R.id.rl_park_fee)
    RelativeLayout rlParkFee;
    @BindView(R.id.tv_inUse_caokong)
    TextView tvInUseCaokong;
    @BindView(R.id.driving_recharge_tv)
    MarqueeTextview drivingRechargeTv;
    @BindView(R.id.driving_tip_ll)
    LinearLayout drivingTipLl;
    @BindView(R.id.driving_recharge_iv)
    ImageView drivingRechargeIv;
    @BindView(R.id.driving_recharge_ll2)
    LinearLayout drivingRechargeLl2;
    @BindView(R.id.driving_gasoline_iv)
    ImageView drivingGasolineIv;
    @BindView(R.id.driving_gasoline_ll2)
    LinearLayout drivingGasolineLl2;
    @BindView(R.id.iv_jiangli)
    ImageView ivJiangli;
    @BindView(R.id.send_car_tel)
    Button sendCarTel;
    @BindView(R.id.imageView_card)
    ImageView imageView_card;
    private String inUseTime = "";
    private double travelDistance;
    private MapView mapView;
    private BaiduMap mBaiduMap;
    private MapStatusUtils mapStatusUtils;
    public LocationClient mLocClient = null;
    private LatLng curPosition;
    private Context mContext = this;
    private String orderId;
    private String orderNum;
    private String carId;
    private int rentType;
    private int bookType;
    private String carLicense;
    private long count = 0;
    private TimerTask task;
    private Timer timer;
    private OverlayUtils overlayUtils;
    private PowerManager.WakeLock wakeLock;
    private List<List<CityBoundBean.AttachmentBean>> cityBoundsInfo;
    private String model;
    private boolean tipBluetooth = true;
    private boolean isPauseLocation = true;//如果用户点了还车，不停止当前的定位，还车页面需要实时的精确的定位
    private PoiSearch mPoiSearch = null;
    public BleConstants.ControlType controlType;
    private boolean isFirstLocation = true;
    private boolean isShowRechargeOrGasolineDot = false;
    private boolean isShowRechargeOrGasolineDotPaoPao = false;
    private CountDownTimer countDownTimer;
    private String Distance = "";
    private int type = 0;
    private List<RechargeDotBean.AttachmentBean.ElectricStationBean> electricStationBeanList;
    private ImageView iv_wallet_reddot, iv_weizhang_reddot;
    private int carType;
    private PoiInfo nearestOilStation;
    private double endurancemileage;//车当前的续航
    private float distanceLimit;
    private float galolineMileage;
    private int searchTimes = 0;
    private List<PoiInfo> totalPoi = new ArrayList<>();
    private String city;
    private String endTime;
    private boolean showBleTip = false;
    private String goldPic;
    private boolean isFirstCheckCarDamage = true;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    count++;
                    if (count > 86400) {
                        //   textViewInUseTime.setText(getSpannableString(TimeUtils.formatMinPlusOne(count + "")));
                        inUseTime = TimeUtils.formatMinPlusOne(count + "");

                    } else {
                        // textViewInUseTime.setText(TimeUtils.formatSecondCount(count + "", 1));
                        inUseTime = TimeUtils.formatSecondCount(count + "", 1).toString();

                    }
                    if (curPosition != null && !isShowRechargeOrGasolineDotPaoPao) {
                        overlayUtils.hideInfoWindow();
                        overlayUtils.showDrivingCarInfoWindow(inUseTime, travelDistance, endTime, curPosition);
                    }


                    if (count % 120 == 0 && count != 0 && !isShowRechargeOrGasolineDotPaoPao) {
                        getTravelDistance();
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override

    public int getLayoutId() {
        return R.layout.activity_car_driving;
    }


    @Override
    public void initCustomMapView() {
        // new MapStatusUtils().setMapCustomFile(this, "custom_config.json");
    }


    @Override
    public void initData() {
        super.initData();
        orderId = getIntent().getStringExtra(IntentKey.INTENT_ORDER_ID);
        carId = getIntent().getStringExtra(IntentKey.INTENT_CAR_ID);
        carLicense = getIntent().getStringExtra(IntentKey.INTENT_CAR_LICENSE);
        EventBus.getDefault().register(this);
        BluetoothHelper.getInstance().removeBleInfo(mContext);
    }

    @Override
    public void initView() {
        if (BuildConfig.DEBUG) {//显示debug模式入口
            findViewById(R.id.debug_entry).setVisibility(View.VISIBLE);
        }
        initRedDot();
        initMap();
        //监听抽屉
        drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                centerUsername.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.USER_NICK));
                if (!"0".equals(SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE))) {
                    ImageLoader.getInstance().displayCricleImage(getApplicationContext(), MyApplication.getInstance().getImageUrl() + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE), imageViewHead);
                } else {
                    ImageLoader.getInstance().displayCricleImage(getApplicationContext(), R.drawable.icon_head, imageViewHead);
                }
                if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.PARK_FEE_ENTRY, 1) == 0) {
                    rlParkFee.setVisibility(View.GONE);
                } else {
                    rlParkFee.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        //侧栏畅行卡是否显示
        if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.CHANG_XING_CARD, 0) == 1) {
            imageView_card.setVisibility(View.VISIBLE);
        } else {
            imageView_card.setVisibility(View.GONE);
        }

        //Ble open door
        /*    String stepFrom = getIntent().getStringExtra(IntentKey.INTENT_STEP);
        if ("findCar".equals(stepFrom) || "ocrCar".equals(stepFrom)) {
        if (getIntent().getIntExtra(IntentKey.INTENT_ISOPENCAR, 0) == 1) {
                //开门供电成功，不做处理
            } else {
                showLoadingDialog();
                //先获取蓝牙信息
                BluetoothHelper.getInstance().getBleInfo(carId, mContext, new BluetoothHelper.OnGetBleResponse() {
                    @Override
                    public void getBleResponse() {
                        if (BluetoothHelper.getInstance().isBleSupported()) {
                            showBleTip = true;
                            String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                            controlType = BleConstants.ControlType.OPEN_DOOR;
                            if (BluetoothHelper.getInstance().isBluetoothOpened()) {
                                if (BluetoothHelper.getInstance().isConnect()) {
                                    BluetoothHelper.getInstance().operateCar(controlType, onOperateCarListener, serialNumber);
                                } else {
                                    BluetoothHelper.getInstance().searchDevice(1, bothSearchResponse, serialNumber);
                                }
                            } else {
                                //蓝牙未开
                                BluetoothHelper.getInstance().openBluetooth(DrivingActivity.this, REQUEST_OPEN_BLE);
                            }
                        } else {
                            //没有蓝牙信息也不做处理
                            dismissLoadingDialog();
                        }
                    }
                });
            }
        }*/

    }

    private void initRedDot() {
        iv_wallet_reddot = (ImageView) findViewById(R.id.iv_wallet_reddot);
        iv_weizhang_reddot = (ImageView) findViewById(R.id.iv_weizhang_reddot);
        checkPeccancy();
        String cachekey = SPUtils.getInstance(mContext).getStringValue(SPKey.CACHE_KEY);
        if (SPUtils.getInstance(mContext).getIntValue(SPKey.DOT_ISEXITE) == 1 && SPUtils.getInstance(mContext).getIntValue(cachekey) == 0) {
            imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center_dot));
            iv_wallet_reddot.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAvatarEvent(AvatarEvent avatarEvent) {
        if (!"0".equals(SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE))) {
            ImageLoader.getInstance().displayCricleImage(getApplicationContext(), MyApplication.getInstance().getImageUrl() + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE), imageViewHead);
            MyApplication.getInstance().options.uiCustomization.rightAvatar = MyApplication.getInstance().getImageUrl() + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE);
        } else {
            ImageLoader.getInstance().displayCricleImage(getApplicationContext(), R.drawable.icon_head, imageViewHead);
            MyApplication.getInstance().options.uiCustomization.rightAvatar = "android.resource://" + mContext.getPackageName() + "/" + R.drawable.icon_head;
        }
        centerUsername.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.USER_NICK));
    }

    public void initMap() {
        mapView = (MapView) findViewById(R.id.car_inuse_map);
        mapView.showZoomControls(false);
        //MapView.setMapCustomEnable(true);

        if (mBaiduMap == null) {
            mBaiduMap = mapView.getMap();
            //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            mBaiduMap.setMyLocationEnabled(false);
            // 开启定位图层
            mBaiduMap.setMyLocationEnabled(true);

            //设置地图交互
            UiSettings uiSettings = mBaiduMap.getUiSettings();
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setOverlookingGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(true);
            // 定位初始化
            mLocClient = new LocationClient(this);
            LocationClientOption option = new LocationClientOption();
            option.setIsNeedAddress(true);
            option.setIsNeedLocationDescribe(true);
            option.setOpenGps(true); // 打开gps
            option.setCoorType("bd09ll"); // 设置坐标类型
            option.setScanSpan(8000);
            mLocClient.setLocOption(option);
            mLocClient.registerLocationListener(mListener);
            mapStatusUtils = new MapStatusUtils(mContext, mBaiduMap);
            overlayUtils = new OverlayUtils(mContext, mBaiduMap);
            LatLng myPosition = new LatLng(Double.parseDouble(MyApplication.getInstance().getCurPosition()[0]), Double.parseDouble(MyApplication.getInstance().getCurPosition()[1]));

            mapStatusUtils.noAnimateMove(myPosition, 12);
            mBaiduMap.setMyLocationData(new MyLocationData.Builder().latitude(myPosition.latitude).longitude(myPosition.longitude).build());

            // 初始化搜索模块，注册搜索事件监听
            mPoiSearch = PoiSearch.newInstance();
            mPoiSearch.setOnGetPoiSearchResultListener(this);
            mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(final Marker marker) {
                    if (marker.getExtraInfo().get("markerType").equals(MarkerOverlay.MarkerType.BOUNDS_ICON.name())) {
                        return false;
                    }
                    showLoadingDialog();
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                        countDownTimer = null;
                    }
                    final Bundle markerInfoBundle = marker.getExtraInfo();
                    isShowRechargeOrGasolineDotPaoPao = true;
                    Distance = new DecimalFormat("0.00km").format(DistanceUtil.getDistance(curPosition, marker.getPosition()) / 1000);
                    if (markerInfoBundle.getString("markerType").equals(MarkerOverlay.MarkerType.RECHARGE_DOT.name()) || (MarkerOverlay.MarkerType.GASOLINE_DOT.name()).equals(markerInfoBundle.getString("markerType"))) {
                        overlayUtils.showFindRechargeDotInfoWindow(Distance, marker.getPosition(), new MarkerOverlay.NaviButtonClickListener() {
                            @Override
                            public void onClick() {
                                showNaviDialog(marker.getPosition());
                            }
                        });
                    }
                    countDownTimer = new CountDownTimer(1200000000, 1000) {
                        @Override
                        public void onTick(long l) {
                            l /= 1000;
                            if ((l % 120 == 0 || l == 1199999) && l != 1200000) {
                                RoutePlan.getInstance().clearDrvingRoutePlanning();
                                RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_DRIVE, curPosition, marker.getPosition(), new RoutePlan.OnRoutePlannedListener() {
                                    @Override
                                    public void onRoutePlanSuccess(int distance, int duration) {
                                        dismissLoadingDialog();
                                        Distance = new DecimalFormat("0.00km").format(distance / 1000);
                                        overlayUtils.showFindRechargeDotInfoWindow(Distance, marker.getPosition(), new MarkerOverlay.NaviButtonClickListener() {
                                            @Override
                                            public void onClick() {
                                                showNaviDialog(marker.getPosition());
                                            }
                                        });
                                    }

                                    @Override
                                    public void onRoutePlanFailure() {
                                        dismissLoadingDialog();
                                    }
                                });
                            } else if (l == (1200000 - 20)) {
                                dismissLoadingDialog();
                            }
                        }

                        @Override
                        public void onFinish() {
                            RoutePlan.getInstance().clearDrvingRoutePlanning();
                            RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_DRIVE, curPosition, marker.getPosition(), new RoutePlan.OnRoutePlannedListener() {
                                @Override
                                public void onRoutePlanSuccess(int distance, int duration) {
                                    dismissLoadingDialog();
                                    Distance = new DecimalFormat("0.00km").format(distance / 1000);
                                    overlayUtils.showFindRechargeDotInfoWindow(Distance, marker.getPosition(), new MarkerOverlay.NaviButtonClickListener() {
                                        @Override
                                        public void onClick() {
                                            showNaviDialog(marker.getPosition());
                                        }
                                    });
                                }

                                @Override
                                public void onRoutePlanFailure() {
                                    dismissLoadingDialog();
                                }
                            });
                        }
                    };
                    countDownTimer.start();
                    return true;
                }
            });

            mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus) {
                }

                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

                }

                @Override
                public void onMapStatusChange(MapStatus mapStatus) {
                }

                @Override
                public void onMapStatusChangeFinish(MapStatus mapStatus) {
                    overlayUtils.addBoundsDriving();

                }
            });

            mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    if (isShowRechargeOrGasolineDotPaoPao) {
                        RoutePlan.getInstance().clearDrvingRoutePlanning();
                        overlayUtils.hideInfoWindow();
                        isShowRechargeOrGasolineDotPaoPao = false;
                    }
                }

                @Override
                public boolean onMapPoiClick(MapPoi mapPoi) {
                    return false;
                }
            });
            //startLocation();
        }
    }

    private String message = "";

    @OnClick({R.id.driving_gasoline_ll2, R.id.rl_weizhang, R.id.driving_recharge_ll2, R.id.tv_inUse_caokong, R.id.driving_car_close, R.id.driving_car_open, R.id.driving_car_return,
            R.id.driving_car_find, R.id.imageView_locate, R.id.tv_current_fee, R.id.park_fee_tip, R.id.imageView_center, R.id.myInfo_oil,
            R.id.info_image_head, R.id.myInfo_route, R.id.myInfo_wallet, R.id.myInfo_service, R.id.myInfo_guide, R.id.rl_park_fee,
            R.id.myInfo_invite, R.id.rl_setting, R.id.debug_entry, R.id.send_car_tel, R.id.imageView_card})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) return;    //判断是否多次点击
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.driving_gasoline_ll2:
                if (type % 2 == 0) {
                    isShowRechargeOrGasolineDot = false;
                    isShowRechargeOrGasolineDotPaoPao = false;
                    drivingGasolineLl2.setBackground(getResources().getDrawable(R.drawable.icon_gasoline_off));
                    overlayUtils.removeGasolineDotMarker();
                    RoutePlan.getInstance().clearDrvingRoutePlanning();
                } else {
                    if (!isShowRechargeOrGasolineDot) {
                        getGasolineDot();
                    }
                }
                type++;
                break;
            case R.id.driving_recharge_ll2:
                if (type % 2 == 0) {
                    isShowRechargeOrGasolineDot = false;
                    isShowRechargeOrGasolineDotPaoPao = false;
                    drivingRechargeLl2.setBackground(getResources().getDrawable(R.drawable.drving_recharge_bg_off));
                    overlayUtils.removeRechargeDotMarker();
                    RoutePlan.getInstance().clearDrvingRoutePlanning();
                } else {
                    if (!isShowRechargeOrGasolineDot) {
                        getRechargeDot();
                    }
                }
                type++;
                break;
            case R.id.driving_car_find:
                findCar(orderId, carId);
                break;
            case R.id.driving_car_close:
                message = "正在关车门...";
                showLoadingDialog(message);
                showBleTip = false;
                controlType = BleConstants.ControlType.CLOSE_DOOR;
                if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                    //蓝牙开，未连接
                    if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                        String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                        BluetoothHelper.getInstance().searchDevice(1, bothSearchResponse, serialNumber);
                        //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "connect", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);

                    }
                    //蓝牙开，已连接
                    else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                        String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                        BluetoothHelper.getInstance().operateCar(controlType, onOperateCarListener, serialNumber);
                        //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "close", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);

                    }
                    //蓝牙未开
                    else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                        lockCarOff(orderId, carId);
                    }
                } else {
                    lockCarOff(orderId, carId);
                }
                break;
            case R.id.driving_car_open:
                checkCarDamage(new OnCheckDamageListener() {
                    @Override
                    public void onHaveRecord() {
                        message = "正在开车门...";
                        showLoadingDialog(message);
                        showBleTip = false;
                        controlType = BleConstants.ControlType.OPEN_DOOR;
                        if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                            //蓝牙开，未连接
                            if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                                String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                                BluetoothHelper.getInstance().searchDevice(1, bothSearchResponse, serialNumber);
                                //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "connect", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);

                            }
                            //蓝牙开，已连接
                            else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                                String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                                BluetoothHelper.getInstance().operateCar(controlType, onOperateCarListener, serialNumber);
                                //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "close", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);

                            }
                            //蓝牙未开
                            else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                                lockCarOn(orderId, carId);
                            }
                        } else {
                            lockCarOn(orderId, carId);
                        }


                    }

                    @Override
                    public void onNoRecord() {
                        intentToCarDamage();
                    }
                });

                break;
            case R.id.driving_car_return:
                isPauseLocation = false;
                if (getPermissionAndGps()) {
                    preReturnCar(orderId, carId, false);
                }
                break;
            case R.id.imageView_locate:
                if (curPosition != null) {
                    mapStatusUtils.animateMove(curPosition, 17, 600);
                }
                break;
            case R.id.tv_current_fee:
                //当前费用
                currentFee(orderId);
                break;
            case R.id.park_fee_tip:
                Intent intent_park = new Intent(mContext, WebViewActivity.class);
                intent_park.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "停车费报销");
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_input_fee), "orderId=" + orderId);
                intent_park.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_input_fee));
                startActivity(intent_park);
                break;
            case R.id.imageView_center:
                drawer.openDrawer(Gravity.START);
                break;
            case R.id.info_image_head:
                drawer.closeDrawer(Gravity.START);
                drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
                    @Override
                    public void onDrawerClosed(View drawerView) {
                        super.onDrawerClosed(drawerView);
                        Intent intent = new Intent(mContext, WebViewActivity.class);
                        intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_personal_center));
                        intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "个人中心");
                        startActivity(intent);
                        drawer.removeDrawerListener(this);
                    }
                });
                break;
            case R.id.myInfo_wallet:
                String cachekey = SPUtils.getInstance(mContext).getStringValue(SPKey.CACHE_KEY);
                SPUtils.getInstance(mContext).putIntValue(cachekey, 1);
                EventBus.getDefault().post(new WalletRedDotBean(true));
                imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center));
                iv_wallet_reddot.setVisibility(View.INVISIBLE);
                Intent intent_wallet = new Intent(mContext, WebViewActivity.class);
                intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的钱包");
                CookieManager cookieManager2 = CookieManager.getInstance();
                cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "isExist=" + SPUtils.getInstance(mContext).getIntValue(SPKey.DOT_ISEXITE));
                cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "RushedSendPicture=" + SPUtils.getInstance(mContext).getStringValue(SPKey.WALLET_PICTURE));
                intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet));
                startActivity(intent_wallet);
                break;
            case R.id.rl_setting:
                drawer.closeDrawer(Gravity.START);
                drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
                    @Override
                    public void onDrawerClosed(View drawerView) {
                        super.onDrawerClosed(drawerView);
                        Intent intent = new Intent();
                        intent.setClass(mContext, WebViewActivity.class);
                        intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "设置");
                        intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_setting));
                        startActivity(intent);
                    }
                });

                break;
            case R.id.myInfo_oil:
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的油箱");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_gasoline));
                startActivity(intent);
                break;
            case R.id.myInfo_route:
                if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.WEB_ORDER_HISTORY, 1) == 0) {
                    intent.setClass(mContext, TravelRecordActivity.class);
                    startActivity(intent);
                } else {
                    intent.setClass(mContext, WebViewActivity.class);
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的订单");
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_order_list));
                    startActivity(intent);
                }
                break;
            case R.id.myInfo_invite:
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "邀请好友");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_share_third));
                startActivity(intent);
                break;
            case R.id.myInfo_guide:
                String title = "用户指南";
                intent = new Intent(getApplicationContext(), WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, title);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_guide));
                startActivity(intent);
                break;
            case R.id.myInfo_service:
                /*if (Unicorn.isServiceAvailable()) {
                    ConsultService consultService = new ConsultService(mContext);
                    consultService.consultService(mContext, "", "", "", null);
                } else {
                    intent.setClass(mContext, ContactServiceActivity.class);
                    startActivity(intent);
                }*/
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "大道客服");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.HTML_QIMO + "userId=" + ((MyApplication) getApplication()).getUid() + "&nickName=" + centerUsername.getText().toString() + "&phone=" + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PHONE_NUM));
                startActivity(intent);
                break;
            case R.id.tv_inUse_caokong:
                if (model != null) {
                    intent = new Intent();
                    intent.setClass(mContext, WebViewActivity.class);
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "操控介绍");
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_operation_guide_new) + model.toUpperCase() + ".html");
                    startActivity(intent);
                }
                break;
            case R.id.rl_weizhang:
                if (!NetUtils.isNetworkAvailable(mContext)) {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    return;
                }
                notifyPeccancy();
                imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center));
                iv_weizhang_reddot.setVisibility(View.INVISIBLE);
                EventBus.getDefault().post(new PecancyRedDotBean(true));
                Intent intent_weizhang = new Intent(mContext, WebViewActivity.class);
                intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "违章查询");
                intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_break_rules));
                startActivity(intent_weizhang);
                break;
            case R.id.rl_park_fee:
                Intent intent_parkFee = new Intent(mContext, WebViewActivity.class);
                intent_parkFee.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "停车费查询");
                intent_parkFee.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_parkingFee_list) + "?appVersion=" + MyApplication.getInstance().getAppVersion());
                startActivity(intent_parkFee);
                break;
            case R.id.debug_entry:
                intent.setClass(mContext, DebugModeActivity.class);
                startActivity(intent);
                break;
            case R.id.send_car_tel:
                getTel();
                break;
            case R.id.imageView_card:
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的畅行卡");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_discountCardValidRecord));
                startActivity(intent);
                break;
        }
    }

    private void intentToCarDamage() {
        //跳转车损
        Intent intent = new Intent(mContext, WebViewActivity.class);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_car_damage_report), "licenseTag=" + carLicense);
        cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_car_damage_report), "orderId=" + orderId);
        cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_car_damage_report), "carId=" + carId);
        cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_car_damage_report), "phoneNum=" + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PHONE_NUM));
        intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_car_damage_report) + "?oid=" + orderId);
        intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "车损拍照");
        startActivity(intent);
    }

    private void getTel() {
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("orderId", orderId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 5).getSendTel(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SendTelBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(SendTelBean sendTelBean) {
                        if (sendTelBean.getStatus() == 200) {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + sendTelBean.getAttachment().getPhone()));
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + SPUtils.getInstance(mContext).getStringValue(SPKey.HOT_LINE)));
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private boolean getPermissionAndGps() {
        boolean permissionOk;
        boolean gpsOk;
        permissionOk = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断是否开启了GPS，如果没有则开启
        gpsOk = (locationManager == null) || (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));

        if (!permissionOk) {
            DialogTwoButton dialogButton = new DialogTwoButton(mContext);
            dialogButton.setTitle("定位权限已关闭");
            dialogButton.setMessage("您需要开启定位权限，才可以查看车辆情况，请到设置的权限管理中开启【大道用的】定位权限。");
            dialogButton.setCancelable(false);
            dialogButton.setCanceledOnTouchOutside(false);
            dialogButton.setYesOnclickListener("设置", () -> {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
                dialogButton.dismiss();
            });
            dialogButton.setNoOnclickListener("取消", () -> {
                dialogButton.dismiss();
            });
            dialogButton.show();
            return false;
        }

        if (!gpsOk) {
            DialogTwoButton inCarDialog = new DialogTwoButton(this);
            inCarDialog.setTitle("GPS定位已关闭");
            inCarDialog.setMessage(getString(R.string.LocationServiceRemind));
            inCarDialog.setYesOnclickListener("设置", () -> {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, Constants.REQUEST_LOCATION_SERVICE);
                inCarDialog.dismiss();
            });
            inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
            inCarDialog.setCanceledOnTouchOutside(true);
            inCarDialog.setCancelable(true);
            inCarDialog.show();
            return false;
        }
        return true;
    }

    private void notifyPeccancy() {
        String uid = SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID);
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).notifyPeccancy(MyApplication.getInstance().getRequestFieldMap(), uid).enqueue(new Callback<CheckPeccancyBean>() {
            @Override
            public void onResponse(Call<CheckPeccancyBean> call, Response<CheckPeccancyBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getCode() == 200) {

                    } else {
                        //ToastUtils.makeText(mContext, response.body().getMessage() + "。", ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    //ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CheckPeccancyBean> call, Throwable t) {
                //ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });

    }

    private void checkPeccancy() {
        String uid = SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID);
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkPeccancy(MyApplication.getInstance().getRequestFieldMap(), uid).enqueue(new Callback<CheckPeccancyBean>() {
            @Override
            public void onResponse(Call<CheckPeccancyBean> call, Response<CheckPeccancyBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (response.body().getData().isIs_new()) {
                            imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center_dot));
                            iv_weizhang_reddot.setVisibility(View.VISIBLE);
                        }
                    } else {
                        //ToastUtils.makeText(mContext, response.body().getMessage() + "。", ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    //ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CheckPeccancyBean> call, Throwable t) {
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });

    }


    private void preReturnCar(final String orderId, final String carId, boolean isReturn) {

        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).intentReturnCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, isReturn + "").enqueue(new Callback<ReturnCarBean>() {
            @Override
            public void onResponse(Call<ReturnCarBean> call, Response<ReturnCarBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        intentReturnCar(orderId, carId);
                    } else if (response.body().getStatus() == 410) {
                        final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
                        dialogOneButton.setTitle("车辆续航已不足");
                        dialogOneButton.setMessage(response.body().getMessage());
                        dialogOneButton.setCancelable(false);
                        dialogOneButton.setCanceledOnTouchOutside(false);
                        dialogOneButton.setYesOnclickListener("知道了", new DialogOneButton.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                dialogOneButton.dismiss();
                            }
                        });
                        dialogOneButton.show();
                    } else if (response.body().getStatus() == 600) {
                        DialogTwoButton dialogTip = new DialogTwoButton(mContext);
                        dialogTip.setMessage(response.body().getMessage());
                        dialogTip.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                dialogTip.dismiss();
                            }
                        });
                        dialogTip.setYesOnclickListener("继续", new DialogTwoButton.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                dialogTip.dismiss();
                                preReturnCar(orderId, carId, true);
                            }
                        });
                        dialogTip.show();
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ReturnCarBean> call, Throwable t) {
                Logger.i("driving intentToCarDamage return", "onFaliure" + t.getMessage());
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void intentReturnCar(String orderId, String carId) {
        if (carType != 2) {//非油车不做续航判断
            Intent intent = new Intent(DrivingActivity.this, ReturnCarActivity.class);
            intent.putExtra("orderId", orderId);
            intent.putExtra("carId", carId);
            intent.putExtra("rentType", rentType);
            intent.putExtra("bookType", bookType);
            intent.putExtra("orderNum", orderNum);
            startActivity(intent);
            Logger.d("retrunCar", "electricity car can return");
            return;
        }

        //还车时车和加油站的最大距离要求
        distanceLimit = SPUtils.getInstance(mContext).getFloatValue(SPKey.GASOLINE_LIMIT);
        //还车时车最低续航要求
        galolineMileage = SPUtils.getInstance(mContext).getFloatValue(SPKey.GASOLINE_MILEAGE);
        PoiInfo nearestOilStation = null;//最近的加油站的数据
        double carAndOilStationDistance = 0;//车和加油站的距离
        if (totalPoi != null && totalPoi.size() != 0) {
            nearestOilStation = getNearstStation(totalPoi);
            carAndOilStationDistance = DistanceUtil.getDistance(curPosition, nearestOilStation.location);
        }
        if ((distanceLimit >= 0 && galolineMileage >= 0) && (endurancemileage <= galolineMileage) && (carAndOilStationDistance > distanceLimit)) {//需要执行续航判断 且 不满足续航要求 且 离加油站远
            dismissLoadingDialog();
            final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
            dialogOneButton.setTitle("车辆续航已不足");
            dialogOneButton.setMessage("请将车辆行驶至加油站还车");
            dialogOneButton.setCancelable(false);
            dialogOneButton.setCanceledOnTouchOutside(false);
            dialogOneButton.setYesOnclickListener("知道了", () -> dialogOneButton.dismiss());
            dialogOneButton.show();
            Logger.d("retrunCar", "oil car cannot return");
            ParseApiStore.getInstance().commitOilLowLog(carId, orderId, curPosition, nearestOilStation == null ? new LatLng(0, 0) : nearestOilStation.location, endurancemileage + "", carAndOilStationDistance + "", "0", galolineMileage + "", distanceLimit + "");

        } else {
            dismissLoadingDialog();
            Intent intent = new Intent(DrivingActivity.this, ReturnCarActivity.class);
            intent.putExtra("orderId", orderId);
            intent.putExtra("carId", carId);
            intent.putExtra("rentType", rentType);
            intent.putExtra("bookType", bookType);
            intent.putExtra("orderNum", orderNum);
            startActivity(intent);
            Logger.d("retrunCar", "oil car can return");
            ParseApiStore.getInstance().commitOilLowLog(carId, orderId, curPosition, nearestOilStation == null ? new LatLng(0, 0) : nearestOilStation.location, endurancemileage + "", carAndOilStationDistance + "", "1", galolineMileage + "", distanceLimit + "");

        }
    }

    private void getRechargeDot() {
        drivingRechargeLl2.setClickable(false);
        showLoadingDialog();
        isShowRechargeOrGasolineDot = true;
        drivingRechargeLl2.setBackground(getResources().getDrawable(R.drawable.drving_recharge_bg_on));
        if (electricStationBeanList != null) {
            overlayUtils.addReChargeDotMarker(electricStationBeanList);
            dismissLoadingDialog();
            drivingRechargeLl2.setClickable(true);
        } else {
            ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getRechargeDot(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<RechargeDotBean>() {
                @Override
                public void onResponse(Call<RechargeDotBean> call, final Response<RechargeDotBean> response) {
                    drivingRechargeLl2.setClickable(true);
                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().getStatus() == 200) {
                            electricStationBeanList = response.body().getAttachment().getElectricStation();
                            overlayUtils.addReChargeDotMarker(response.body().getAttachment().getElectricStation());
                            dismissLoadingDialog();
                        } else if (response.body().getStatus() == 20) {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                            Intent intent = new Intent(mContext, LoginActivity.class);
                            startActivity(intent);
                            AppManager.getAppManager().finishAllActivity();
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                        }
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<RechargeDotBean> call, Throwable t) {
                    Logger.d("netError", t.toString());
                    dismissLoadingDialog();
                    drivingRechargeLl2.setClickable(true);
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void getGasolineDot() {
        drivingGasolineLl2.setClickable(false);
        showLoadingDialog();
        isShowRechargeOrGasolineDot = true;
        drivingGasolineLl2.setBackground(getResources().getDrawable(R.drawable.icon_galoline_on));
        if (totalPoi != null && totalPoi.size() != 0) {
            overlayUtils.addGasolineDotMarker(totalPoi);
            drivingGasolineLl2.setClickable(true);
            dismissLoadingDialog();
        } else {
            searchTimes = 0;
            totalPoi.clear();
            city = "" + SPUtils.getInstance(mContext).getStringValue(SPKey.CITY);
            mPoiSearch.searchInCity(new PoiCitySearchOption()
                    .city(city)
                    .keyword("中石化")
                    .pageCapacity(50)
                    .pageNum(0));
            searchTimes++;
        }

    }

    BluetoothHelper.BothSearchResponse bothSearchResponse = new BluetoothHelper.BothSearchResponse() {
        @Override
        public void onSearchSuccess(String mac, String bleName, String serialNumber) {
            String time = new Date().getTime() / 1000 + "";
            BluetoothHelper.getInstance().connectDevice(connectResponse, 1);
        }

        @Override
        public void onSearchTimeout(String serialNumber) {
            dismissLoadingDialog();
            Logger.i("bleinfo", "扫描超时,行驶中");
            //ParseApiStore.getInstance().commitBleResLog(serialNumber, "connect", "fail", "扫描超时,行驶中", null, BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            if (controlType == BleConstants.ControlType.CLOSE_DOOR) {
                if (showBleTip) {
                    ToastUtils.makeText(mContext, "关门失败，请靠近车辆再次尝试", ToastUtils.LENGTH_LONG).show();
                } else {
                    showLoadingDialog(message);//蓝牙失败开始网络
                    lockCarOff(orderId, carId);
                }
            } else if (controlType == BleConstants.ControlType.OPEN_DOOR) {
                if (showBleTip) {
                    ToastUtils.makeText(mContext, "开门失败，请靠近车辆再次尝试", ToastUtils.LENGTH_LONG).show();
                } else {
                    showLoadingDialog(message);//蓝牙失败开始网络
                    lockCarOn(orderId, carId);
                }
            }
        }

        @Override
        public void onSearchTimeoutEveryTime(String serialNumber) {
            Logger.i("bleinfo", "扫描超时times");
        }
    };

    /**
     * 蓝牙连接的结果
     */
    BluetoothHelper.BothConnectResponse connectResponse = new BluetoothHelper.BothConnectResponse() {
        @Override
        public void onConnectSuccess(String serialNumber) {
            Logger.i("bleinfo", "连接上了");
            //ParseApiStore.getInstance().commitBleResLog(serialNumber, "connect", "success", null, null, BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            // 连接上立即发送数据会失败
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //再次刷新请求信息
                    String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                    BluetoothHelper.getInstance().operateCar(controlType, onOperateCarListener, serialNumber);
                    if (controlType == BleConstants.ControlType.CLOSE_DOOR) {
                        //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "close", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
                    } else if (controlType == BleConstants.ControlType.OPEN_DOOR) {
                        //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "openPowerOn", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
                    }
                }
            }, 1100);
        }

        @Override
        public void onConnectFailed(String error, String response, String serialNumber) {
            dismissLoadingDialog();
            Logger.i("bleinfo", "连接失败,行驶中");
            //ParseApiStore.getInstance().commitBleResLog(serialNumber, "connect", "fail", "连接失败,行驶中", response + "", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            if (controlType == BleConstants.ControlType.CLOSE_DOOR) {
                if (showBleTip) {
                    ToastUtils.makeText(mContext, "关门失败，请靠近车辆再次尝试", ToastUtils.LENGTH_LONG).show();
                } else {
                    showLoadingDialog(message);//蓝牙失败开始网络
                    lockCarOff(orderId, carId);
                }
            } else if (controlType == BleConstants.ControlType.OPEN_DOOR) {
                if (showBleTip) {
                    ToastUtils.makeText(mContext, "开门失败，请靠近车辆再次尝试", ToastUtils.LENGTH_LONG).show();
                } else {
                    showLoadingDialog(message);//蓝牙失败开始网络
                    lockCarOn(orderId, carId);
                }
            }
        }

        @Override
        public void onConnectTimeoutEveryTime(String serialNumber) {
            Logger.i("bleinfo", "连接超时一次");
        }
    };
    BluetoothHelper.OnOperateCarListener onOperateCarListener = new BluetoothHelper.OnOperateCarListener() {
        @Override
        public void onOperateSuccess(int[] status, String response, String serialNumber) {
            dismissLoadingDialog();
            if (controlType == BleConstants.ControlType.CLOSE_DOOR) {
                ToastUtils.makeText(mContext, "关门成功", ToastUtils.LENGTH_LONG).show();
                //ParseApiStore.getInstance().commitBleResLog(serialNumber, "close", "success", null, response + "", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            } else if (controlType == BleConstants.ControlType.OPEN_DOOR) {
                ToastUtils.makeText(mContext, "开门成功", ToastUtils.LENGTH_LONG).show();
                //ParseApiStore.getInstance().commitBleResLog(serialNumber, "openPowerOn", "success", null, response + "", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);

            } else {
                ToastUtils.makeText(mContext, "操作成功", ToastUtils.LENGTH_LONG).show();
            }
        }

        @Override
        public void onOperateFailure(String error, String response, String serialNumber) {
            dismissLoadingDialog();
            if (controlType == BleConstants.ControlType.CLOSE_DOOR) {
                if (showBleTip) {
                    ToastUtils.makeText(mContext, "关门失败，请靠近车辆再次尝试", ToastUtils.LENGTH_LONG).show();
                } else {
                    showLoadingDialog(message);//蓝牙失败开始网络
                    lockCarOff(orderId, carId);
                }
                //ParseApiStore.getInstance().commitBleResLog(serialNumber, "close", "fail", error + "", response + "", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            } else if (controlType == BleConstants.ControlType.OPEN_DOOR) {
                if (showBleTip) {
                    ToastUtils.makeText(mContext, "开门失败，请靠近车辆再次尝试", ToastUtils.LENGTH_LONG).show();
                } else {
                    showLoadingDialog(message);//蓝牙失败开始网络
                    lockCarOn(orderId, carId);
                }
                //ParseApiStore.getInstance().commitBleResLog(serialNumber, "openPowerOn", "fail", error + "", response + "", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_OPEN_BLE) {
                showLoadingDialog();
                String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                BluetoothHelper.getInstance().searchDevice(1, bothSearchResponse, serialNumber);
            }
        } else {
            dismissLoadingDialog();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onResume() {
        super.onResume();
        isPauseLocation = true;
        mapView.onResume();
        startLocation();
        BluetoothHelper.getInstance().unregisterBluetoothStateListener();
        if (!BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
            BluetoothHelper.getInstance().getBleInfo(carId, mContext, null);
        }
        getOrderDetail();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        //如果用户点了还车，不停止当前的定位，还车页面需要实时的精确的定位
        if (isPauseLocation) {
            mLocClient.stop();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    private void getOrderDetail() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getTravelDetail(MyApplication.getInstance().getRequestFieldMap(), orderId)
                .enqueue(new Callback<TravelDetailBean>() {
                    @Override
                    public void onResponse(Call<TravelDetailBean> call, Response<TravelDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                carType = response.body().getAttachment().getCarModel().getType();
                                TravelDetailBean.AttachmentBean result = response.body().getAttachment();
                                if ("2".equals(result.getCarModel().getSupplier_id())) {
                                    BluetoothHelper.getInstance().carType = BleConstants.CarType.ZHI_XIN_TONG;
                                } else if ("4".equals(result.getCarModel().getSupplier_id())) {
                                    BluetoothHelper.getInstance().carType = BleConstants.CarType.YUN_CHE;
                                }
                                rentType = result.getRentType();
                                bookType = result.getBookType();
                                carId = result.getCarModel().getId();
                                orderNum = result.getOrderNum();
                                carLicense = result.getCarModel().getLicenseTag();
                                tvInUseLicense.setText(carLicense);
                                model = result.getCarModel().getModel() + "";
                                //0没有输入过停车费  1已提交  2第一次提交异常  3第二次提交异常
                                if ("0".equals(response.body().getAttachment().getParkFeeStatus()) || "2".equals(response.body().getAttachment().getParkFeeStatus())) {
                                    parkFeeTip.setVisibility(View.VISIBLE);
                                } else {
                                    parkFeeTip.setVisibility(View.GONE);
                                }

                                if (result.getStartBillingTime() <= 0) {
                                    count = 1;
                                } else {
                                    count = (int) ((result.getCurrentTime() - result.getStartBillingTime()) / 1000) + 1;
                                }
                                if (count < 0) {
                                    count = 1;
                                }
                                if (count > 86400) {
                                    // textViewInUseTime.setText(getSpannableString(TimeUtils.formatMinPlusOne(count + "")));
                                    inUseTime = TimeUtils.formatMinPlusOne(count + "");

                                } else {
                                    //textViewInUseTime.setText(TimeUtils.formatSecondCount(count + "", 1)).toString();
                                    inUseTime = TimeUtils.formatSecondCount(count + "", 1).toString();

                                }
                                if (!isShowRechargeOrGasolineDotPaoPao) {
                                    overlayUtils.showDrivingCarInfoWindow(inUseTime, travelDistance, endTime,
                                            new LatLng(Double.parseDouble(MyApplication.getInstance().getCurPosition()[0]),
                                                    Double.parseDouble(MyApplication.getInstance().getCurPosition()[1])));
                                }

                                if (bookType == 4) {//送车上门
                                    sendCarTel.setVisibility(View.VISIBLE);
                                } else {
                                    sendCarTel.setVisibility(View.GONE);
                                }

                                countTime();
                                if (isFirstCheckCarDamage) {
                                    isFirstCheckCarDamage = false;
                                    checkCarDamage(new OnCheckDamageListener() {
                                        @Override
                                        public void onNoRecord() {
                                            intentToCarDamage();
                                        }

                                        @Override
                                        public void onHaveRecord() {

                                        }
                                    });

                                    Glide.with(getApplicationContext()).load(((MyApplication) MyApplication.getInstance()).getImageUrl() + result.getCarModel().getCarIcon()).asBitmap().override(120, 120).into(new SimpleTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                                                    MyLocationConfiguration.LocationMode.NORMAL, true,
                                                    BitmapDescriptorFactory.fromBitmap(resource), 0x00000000, 0x00000000));
                                        }
                                    });
                                }


                                getTravelDistance();
                            } else if (response.body().getStatus() == 20) {
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<TravelDetailBean> call, Throwable t) {
                    }
                });

    }

    interface OnCheckDamageListener {
        void onNoRecord();

        void onHaveRecord();
    }


    private void checkCarDamage(OnCheckDamageListener onCheckDamageListener) {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkCarDamage(orderId).enqueue(new Callback<CarDamageBean>() {
            @Override
            public void onResponse(Call<CarDamageBean> call, Response<CarDamageBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null && response.body().getResult() != null && response.body().getResult().getCode() == 500) {
                    onCheckDamageListener.onNoRecord();
                } else {
                    onCheckDamageListener.onHaveRecord();
                }
            }

            @Override
            public void onFailure(Call<CarDamageBean> call, Throwable t) {
                ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
                dismissLoadingDialog();
            }
        });
    }

    private void getTravelDistance() {
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getTravelDistance(MyApplication.getInstance().getRequestFieldMap(), orderId, carId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext((Function<Throwable, ObservableSource<TravelDistanceBean>>) throwable ->
                        Observable.create(emitter -> {//接口错误返回一个空对象
                            emitter.onNext(new TravelDistanceBean());
                            emitter.onComplete();
                        }))
                .subscribe((new Observer<TravelDistanceBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(TravelDistanceBean travelDistanceBean) {
                        if (travelDistanceBean != null && travelDistanceBean.getStatus() == 200) {
                            if (travelDistanceBean.getAttachment().getLcdNum() > 0) {
                                getGoldInfo();
                            } else {
                                ivJiangli.setVisibility(View.GONE);
                            }
                            travelDistance = travelDistanceBean.getAttachment().getMileage();
                            endurancemileage = travelDistanceBean.getAttachment().getEndurancemileage();
                            endTime = travelDistanceBean.getAttachment().getEndTime();
                            int isNormal = travelDistanceBean.getAttachment().getIsNormal();
                            if (isNormal == 1) {//添加充电桩
                                drivingTipLl.setVisibility(View.VISIBLE);
                                drivingRechargeLl2.setVisibility(View.VISIBLE);
                                drivingRechargeTv.setText(travelDistanceBean.getAttachment().getRemindElectrictyText());
                                if (!isShowRechargeOrGasolineDot && type % 2 == 0) {
                                    getRechargeDot();
                                }
                            } else if (isNormal == 2) {//添加加油站
                                drivingTipLl.setVisibility(View.VISIBLE);
                                drivingGasolineLl2.setVisibility(View.VISIBLE);
                                drivingRechargeTv.setText(travelDistanceBean.getAttachment().getRemindElectrictyText());
                                if (!isShowRechargeOrGasolineDot && type % 2 == 0) {
                                    getGasolineDot();
                                }
                            } else {
                                drivingTipLl.setVisibility(View.INVISIBLE);
                                drivingRechargeLl2.setVisibility(View.INVISIBLE);
                                drivingGasolineLl2.setVisibility(View.INVISIBLE);
                                isShowRechargeOrGasolineDot = false;
                                isShowRechargeOrGasolineDotPaoPao = false;
                                //mBaiduMap.clear();
                                    /*if (overlayUtils != null) {
                                        overlayUtils.addBounds(cityBoundsInfo, true);
                                    }*/
                            }
                            if (curPosition != null) {
                                if (!isShowRechargeOrGasolineDotPaoPao) {
                                    overlayUtils.hideInfoWindow();
                                    overlayUtils.showDrivingCarInfoWindow(inUseTime, travelDistance, endTime, curPosition);
                                }
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                }));
    }

    private void getGoldInfo() {
        //获取金豆车信息
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getGoldOneCar(MyApplication.getInstance().getRequestFieldMap(), carId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GoldCarOneBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(GoldCarOneBean goldCarOneBean) {
                        try {
                            if (goldCarOneBean != null && goldCarOneBean.getMsg_code() == 200 && goldCarOneBean.getAttachment() != null) {
                                goldPic = OverlayUtils.goldBeanInfoMap.get(goldCarOneBean.getAttachment().getGold_car_type()).get("real_time_icon");
                                ImageLoader.getInstance().displayImage(getApplicationContext(), MyApplication.getInstance().getImageUrl() + goldPic, R.drawable.icon_jiangli, ivJiangli);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ivJiangli.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onError(Throwable e) {
                        ivJiangli.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        //确保是我们的请求
        if (requestCode == Constants.READ_LOCATION_PERMISSION_REQUEST) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else if (grantResults.length == 1 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                final DialogTwoButton inCarDialog = new DialogTwoButton(DrivingActivity.this);
                inCarDialog.setMessage("您已拒绝定位权限");
                inCarDialog.setYesOnclickListener("确定", new DialogTwoButton.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        inCarDialog.dismiss();
                        startLocation();
                    }
                });
                inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        dismissLoadingDialog();
                        inCarDialog.dismiss();
                    }
                });
                inCarDialog.setCancelable(false);
                inCarDialog.show();

            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    private void lockCarOn(final String orderId, final String carId) {
        Logger.i("bleinfo", "开始网络开车门");
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).openCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, "0").enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Logger.i("driving net openDoor", new Gson().toJson(response.body()));
                    if (response.body().getStatus() == 200) {
                        Logger.d("bleinfo", "开始网络开车门成功");
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, "开门成功", ToastUtils.LENGTH_SHORT).show();
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        bleOperateWhenNetFail();
                    }
                } else {
                    bleOperateWhenNetFail();
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                Logger.i("driving net openDoor", "onFaliure" + t.getMessage());
                bleOperateWhenNetFail();
            }
        });
    }

    private void lockCarOff(final String orderId, final String carId) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).lockCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, "0").enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Logger.i("driving net closeDoor", new Gson().toJson(response.body()));
                    if (response.body().getStatus() == 200) {
                        Logger.d("bleinfo", "开始网络关车门成功");
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, "关门成功", ToastUtils.LENGTH_SHORT).show();
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        bleOperateWhenNetFail();
                    }
                } else {
                    bleOperateWhenNetFail();
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                Logger.i("driving net closeDoor", "onFaliure" + t.getMessage());
                bleOperateWhenNetFail();
            }
        });
    }

    public void bleOperateWhenNetFail() {
        if (BluetoothHelper.getInstance().isBleSupported()) {
            showBleTip = true;
            if (BluetoothHelper.getInstance().isBluetoothOpened()) {
                String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                if (BluetoothHelper.getInstance().isConnect()) {
                    BluetoothHelper.getInstance().operateCar(controlType, onOperateCarListener, serialNumber);
                } else {
                    BluetoothHelper.getInstance().searchDevice(1, bothSearchResponse, serialNumber);
                }
            } else {
                final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                inCarDialog.setTitle("蓝牙未开启");
                if (controlType == BleConstants.ControlType.CLOSE_DOOR) {
                    inCarDialog.setMessage("靠近车辆，蓝牙关门更顺畅");
                } else {
                    inCarDialog.setMessage("靠近车辆，蓝牙开门更顺畅");
                }
                inCarDialog.setYesOnclickListener("开启", new DialogTwoButton.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        BluetoothHelper.getInstance().openBluetooth(DrivingActivity.this, REQUEST_OPEN_BLE);
                        inCarDialog.dismiss();
                    }
                });
                inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        dismissLoadingDialog();
                        inCarDialog.dismiss();
                    }
                });
                inCarDialog.show();
            }
        } else {
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "开门失败，请靠近车辆再次尝试", ToastUtils.LENGTH_LONG).show();
        }
    }

    public void findCar(String orderId, String carId) {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).findCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId).enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        ToastUtils.makeText(mContext, "鸣笛成功", ToastUtils.LENGTH_SHORT).show();
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else if (response.body().getStatus() == 404) {
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private SpannableString getSpannableString(String dateString) {
        SpannableString spannableString = new SpannableString(dateString);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), dateString.indexOf("天"), dateString.indexOf("天") + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), dateString.indexOf("小时"), dateString.indexOf("小时") + 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), dateString.indexOf("分钟"), dateString.indexOf("分钟") + 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    private void countTime() {
        if (task == null) {
            task = new TimerTask() {
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendEmptyMessage(1);
                }
            };
        }
        if (timer == null) {
            timer = new Timer(true);
            timer.schedule(task, 0, 1000); //延时0ms后执行，1000ms执行一次
        }
    }

    private void startLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                mLocClient.restart();
            }
        } else {
            mLocClient.restart();
        }

    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissLoadingDialog();
                drivingGasolineLl2.setClickable(true);
            }
        }, 4000);
        if (result != null && result.error == SearchResult.ERRORNO.NO_ERROR && type % 2 == 0) {
            List<PoiInfo> poiInfos = result.getAllPoi();
            totalPoi.addAll(poiInfos);
            overlayUtils.addGasolineDotMarker(poiInfos);
            if (searchTimes == 1) {
                for (int i = 1; i < result.getTotalPageNum(); i++) {
                    mPoiSearch.searchInCity(new PoiCitySearchOption()
                            .city(city)
                            .keyword("中石化")
                            .pageCapacity(50)
                            .pageNum(i));
                    searchTimes++;
                }
            }
        } else if (searchTimes == 1) {
            isShowRechargeOrGasolineDot = false;
            isShowRechargeOrGasolineDotPaoPao = false;
            drivingGasolineLl2.setBackground(getResources().getDrawable(R.drawable.icon_gasoline_off));
            overlayUtils.removeGasolineDotMarker();
            RoutePlan.getInstance().clearDrvingRoutePlanning();
        }
    }

    private PoiInfo getNearstStation(List<PoiInfo> poiInfo) {
        Collections.sort(poiInfo, (o1, o2) -> {
            double d1 = DistanceUtil.getDistance(curPosition, o1.location);
            double d2 = DistanceUtil.getDistance(curPosition, o2.location);
            return Double.compare(d2, d1);
        });
        return poiInfo.get(0);
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }


    //定位结果监听
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (null != bdLocation && (bdLocation.getLocType() == BDLocation.TypeGpsLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation)) {
                Logger.d("locationDr", "ok");
                bdLocation = LocationFilter.Algorithm(bdLocation);//根据历史定位，对定位的结果平滑过滤

                if (!BuildConfig.DEBUG) {
                    if ((null != MyApplication.getInstance().getAreaCode()) && (!MyApplication.getInstance().getAreaCode().equals(bdLocation.getCityCode()))) {
                        getCityInfo();//获取城市信息
                    }
                    curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                    MyApplication.getInstance().setAreaCode(bdLocation.getCityCode());
                    MyApplication.getInstance().setAdCode(bdLocation.getAdCode());
                    DecimalFormat df = new DecimalFormat("#.0000000");
                    MyApplication.getInstance().setCurPosition(df.format(curPosition.latitude), df.format(curPosition.longitude));
                    SPUtils.getInstance(mContext).putStringValue(SPKey.CITY, bdLocation.getCity());
                } else {
                    switch (SPUtils.getInstance(mContext).getIntValue("$s_locationMode")) {
                        case 0:
                        case 1:
                            if ((null != MyApplication.getInstance().getAreaCode()) && (!MyApplication.getInstance().getAreaCode().equals(bdLocation.getCityCode()))) {
                                getCityInfo();//刷新城市信息
                            }
                            curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位

                            MyApplication.getInstance().setAreaCode(bdLocation.getCityCode());
                            MyApplication.getInstance().setAdCode(bdLocation.getAdCode());
                            DecimalFormat df = new DecimalFormat("#.0000000");
                            MyApplication.getInstance().setCurPosition(df.format(curPosition.latitude), df.format(curPosition.longitude));
                            SPUtils.getInstance(mContext).putStringValue(SPKey.CITY, bdLocation.getCity());

                            break;
                        case 2:
                            curPosition = new LatLng(Double.parseDouble(SPUtils.getInstance(mContext).getStringValue("$s_fixLatitude")),
                                    Double.parseDouble(SPUtils.getInstance(mContext).getStringValue("$s_fixLongitude")));// 更新定位
                            MyApplication.getInstance().setAreaCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE));
                            MyApplication.getInstance().setAdCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AD_CODE));
                            MyApplication.getInstance().setCurPosition(SPUtils.getInstance(mContext).getStringValue("$s_fixLatitude"),
                                    SPUtils.getInstance(mContext).getStringValue("$s_fixLongitude"));
                            break;
                    }

                }

                mBaiduMap.setMyLocationData(new MyLocationData.Builder().latitude(curPosition.latitude).longitude(curPosition.longitude).build());
                if (isFirstLocation) {//首次成功的定位
                    isFirstLocation = false;
                    mapStatusUtils.noAnimateMove(curPosition, 11.5f);
                    String boundCache = SDCardUtils.loadFileFromSDCardToStirng(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "boundCache.txt");
                    if (boundCache != null && overlayUtils != null) {
                        Logger.d("boundsDr", "boundCache!=null");
                        overlayUtils.allBounds = new Gson().fromJson(boundCache, CityBoundBean.class).getAttachment().getFenceArea();
                        overlayUtils.addBoundsDriving();
                        Logger.d("boundsDr", "添加完成");
                    }
                    Logger.d("boundsDr", "准备缩放");
                    handler.postDelayed(() -> mapStatusUtils.animateMove(curPosition, 17, 1000), 1500);
                }
            } else {
                Logger.d("locationDr", "errror");
            }
        }
    };

    //获取城市信息
    public void getCityInfo() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getCityInfo(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<CityDetailBean>() {
                    @Override
                    public void onResponse(Call<CityDetailBean> call, Response<CityDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200 && response.body().getAttachment() != null) {
                                if (response.body().getAttachment().getIsClear() == 1) {
                                    SPUtils.getInstance(mContext).removeValue(response.body().getAttachment().getClearCacheKey());
                                }
                                SPUtils.getInstance(mContext).putStringValue(SPKey.CACHE_KEY, response.body().getAttachment().getCacheKey());
                                SPUtils.getInstance(mContext).putStringValue(SPKey.CLEAR_KEY, response.body().getAttachment().getClearCacheKey());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.DOT_ISEXITE, response.body().getAttachment().getIsExist());
                                SPUtils.getInstance(mContext).putStringValue(SPKey.WALLET_PICTURE, response.body().getAttachment().getRushedSendPicture());
                                if (response.body().getAttachment().getIsExist() == 1 && SPUtils.getInstance(mContext).getIntValue(response.body().getAttachment().getCacheKey()) == 0) {
                                    imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center_dot));
                                    iv_wallet_reddot.setVisibility(View.VISIBLE);
                                }
                                SPUtils.getInstance(mContext).putIntValue(SPKey.DEPOSIT_CAR, response.body().getAttachment().getEnclosure().getCarBail());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.IS_ALIPAY_OPEN, response.body().getAttachment().getEnclosure().getAliPay());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.IS_WXPAY_OPEN, response.body().getAttachment().getEnclosure().getWechatPay());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.IS_SHARE_INVITE, response.body().getAttachment().getEnclosure().getActUserShare());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.FIND_CAR_DISTANCE, response.body().getAttachment().getEnclosure().getFindCarDistance());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.IS_CITY_OPEN, response.body().getAttachment().getEnclosure().getIsCar());

                            } else if (response.body().getStatus() == 20) {
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishActivity();
                            }
                          /*  if (response.body().getStatus() != 20 && response.body().getAttachment() != null) {
                                GetAppConfig.getInstance(mContext).getAppConstants();
                            }
*/
                        } else {
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CityDetailBean> call, Throwable t) {
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                        Logger.d("netError", "002");
                    }
                });
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }


    @Override
    protected void onDestroy() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        MapView.setMapCustomEnable(false);
        mapView.onDestroy();

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        mPoiSearch.destroy();
        super.onDestroy();
    }

    @Subscribe
    public void finishActivity(ReturnCarEvent event) {
        if (event.isReturn) {
            AppManager.getAppManager().finishActivity(this);
        }
    }

    //当前订单费用
    public void currentFee(final String orderId) {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getCurrentFee(MyApplication.getInstance().getRequestFieldMap(), orderId).enqueue(new Callback<CurrentFeeBean>() {
            @Override
            public void onResponse(Call<CurrentFeeBean> call, Response<CurrentFeeBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Logger.d("driving cur fee", new Gson().toJson(response.body()));
                    dismissLoadingDialog();
                    if (response.body().getStatus() == 200 && response.body().getAttachment() != null) {
                        final CarCurrentParkFeeDialog dialog = new CarCurrentParkFeeDialog(mContext);
                        dialog.setData(response.body().getAttachment().getList());
                        dialog.show();

                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CurrentFeeBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void showNaviDialog(final LatLng carPosition) {
        final ChooseNaviDialog chooseNaviDialog = new ChooseNaviDialog(mContext);
        chooseNaviDialog.setOnItemClickListener(new ChooseNaviDialog.OnItemClickListener() {
            @Override
            public void onClickItem(int position) {
                if (position == 0) {
                    // 构建 route搜索参数以及策略，起终点也可以用name构造
                    RouteParaOption para = new RouteParaOption()
                            .startPoint(curPosition)
                            .endPoint(carPosition);
                    try {
                        BaiduMapRoutePlan.openBaiduMapDrivingRoute(para, mContext);
                    } catch (Exception e) {
                        ToastUtils.makeText(mContext, "未安装百度地图", ToastUtils.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                } else {
                    LatLng gaoDeCurPosition = BaiduMapParams.gaoDeToBaidu(curPosition);
                    LatLng gaoDeCarPosition = BaiduMapParams.gaoDeToBaidu(carPosition);
                    Intent intent = new Intent();
                    intent.setAction("android.intentToCarDamage.action.VIEW");
                    intent.addCategory("android.intentToCarDamage.category.DEFAULT");
                    intent.setPackage("com.autonavi.minimap");
                    intent.setData(Uri.parse("amapuri://route/plan/?sourceApplication=大道用车&slat=" + gaoDeCurPosition.latitude + "&slon=" + gaoDeCurPosition.longitude + "&dlat=" + gaoDeCarPosition.latitude + "&dlon=" + gaoDeCarPosition.longitude + "&dev=0&t=0"));
                    if (SDCardUtils.checkApkExist(mContext, "com.autonavi.minimap")) {
                        try {
                            startActivity(intent);
                            Log.e("GasStation", "高德地图客户端已经安装");
                        } catch (Exception e) {
                            ToastUtils.makeText(mContext, "启动高德地图失败", ToastUtils.LENGTH_SHORT).show();
                        }

                    } else {
                        ToastUtils.makeText(mContext, "未安装高德地图", ToastUtils.LENGTH_SHORT).show();
                    }
                }
                chooseNaviDialog.dismiss();
            }
        });
        chooseNaviDialog.show();
    }

}
